/*
 * Created by SharpDevelop.
 * User: MyWife
 * Date: 10/11/2009
 * Time: 7:18 PM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Collections;
using popLib;
using System.Threading;
using System.Data;
using System.Diagnostics;
using System.Windows.Forms;
using System.Text;

namespace FileTransferSocket
{
	/// <summary>
	/// Description of Client.
	/// </summary>
	public class Client
	{
		TcpClient tcpClient;
		NetworkStream networkStream;
		string ip; int port;
		
		public delegate void ConnectEvent(string ip);
		public event ConnectEvent ServerConnected;
				
		
		public Client( string ip, int port )
		{
			this.ip = ip;
			this.port = port;
		}
		
		public void Connect(){
			try
			{
				//init client socket
				tcpClient 			 = new TcpClient(ip, port);
				networkStream 		 = tcpClient.GetStream();
                tcpClient.Client.ReceiveBufferSize = Global.Singleton().SocketBufferSize;
                tcpClient.Client.SendBufferSize = Global.Singleton().SocketBufferSize;

				if( ServerConnected!=null)
					ServerConnected( ip );
				Thread current 		 = new Thread(new System.Threading.ParameterizedThreadStart(ProcessServer));
	    		current.IsBackground = true;
	    		current.Start();
	    		
	    		
			}			
			catch(Exception ex)
			{	
				if( ex.ToString().IndexOf("System.Net.Sockets.SocketException: No connection could be made") == -1 )
					FileLib.writeLog( FileLib.getFullPath( "FileLog.txt" ), ex, "Client" );
				else FormLib.alert("Server is not available!");
			}			
		}
		
		private void ProcessServer( object obj ){
			try
			{
                while (true) Global.Singleton().handleStream(tcpClient.Client, networkStream);
			}			
			catch(Exception ex)
			{	
				if( ex.ToString().IndexOf("System.IO.IOException: Unable to read data from") == -1 )
					FileLib.writeLog( FileLib.getFullPath( "FileLog.txt"), ex, "ProcessServer" );
				tcpClient.Close();
			}
			finally
			{
				tcpClient.Close();
			}
		}

        public void SendFile(string file, int currentFileIndex, int totalFiles)
        {
            Global.Singleton().sendFile(file, currentFileIndex, totalFiles,  tcpClient.Client);
        }
        
        public void Shutdown(){
        	networkStream.Dispose();
        	tcpClient.Close();
        }
		
		
	}
}
